package org.dromara.utils;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.file.FileNameUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.formula.functions.T;
import org.dromara.basic.domain.bo.MemberBo;
import org.dromara.basic.domain.vo.FaceImageVo;
import org.dromara.basic.domain.vo.MemberVo;
import org.dromara.basic.domain.vo.TeachClassVo;
import org.dromara.basic.service.ITeachClassService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class FileUploadUtils {

    private static String baseStoreDir;
    @Value("${fileUpload.profile}")
    public void setBaseStoreDir(String path){
        baseStoreDir = path;
    }

    private static ITeachClassService teachClassService;
    @Autowired
    public void setiTeachClassService(ITeachClassService iTeachClassService){
        teachClassService = iTeachClassService;
    }


    public static String uploadFile(MultipartFile file, MemberVo bo) {
        String url =new String();
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String prefix = FileNameUtil.getSuffix(originalFilename);
            String path=baseStoreDir+"/"+bo.getTenantId()+"/"+bo.getFileType();
            if(StringUtils.isNotEmpty(bo.getYears())){
                path=path+"/"+bo.getYears();
                File folder = new File(path);
                if (!folder.exists()) {
                    boolean created = folder.mkdirs();
                    if (!created) {
                        throw new ServiceException("文件上传失败");
                    }
                }
            }
            // 时间格式化格式
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            // 获取当前时间并作为时间戳给文件夹命名
            String timeStamp = simpleDateFormat.format(new Date());
            String newFileName = bo.getIdNumber() + "_" +timeStamp +"."+prefix;
            File uploadFile = new File(path, newFileName); // 完整文件路径
            try {
                file.transferTo(uploadFile);
            }catch (Exception e){
                System.out.println(e);
            }
            url = path+"/"+newFileName;

        }
        return url;
    }

    public static String uploadFiles(List<MultipartFile> files, MemberVo bo) {
        String newFile=new String();
        for (MultipartFile file:files) {
            String upload = uploadFile(file, bo);
            if (StringUtils.isNotEmpty(upload)) {
                if(StringUtils.isNotEmpty(newFile)){
                    newFile+=","+upload;
                }else {
                    newFile=upload;
                }
            }
        }
        return newFile;
    }
    public static void downloadFile(String url, HttpServletResponse response) throws Exception{
        try {
            File file = new File(url);
            if (!file.exists()) {
                throw new FileNotFoundException("文件不存在");
            }
            FileInputStream inputStream = new FileInputStream(file);
            //输出文件
            InputStream fis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            //获取文件的名字再浏览器下载页面
            String name = file.getName();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "iso-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            out.write(buffer);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("文件不存在");
        }catch (Exception e) {
            throw e;
        }
    }
    public static  Boolean delFile(String url){
        File dest = new File(url);
        if (dest.exists()) {
            Boolean isDelete = FileSystemUtils.deleteRecursively(dest);
            if (!isDelete) {
                throw new ServiceException("删除文件失败!");
            }
        }
        return true;
    }

    public static  void upload(HttpServletRequest request,MemberVo bo){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("file");
        TeachClassVo teachClassVo = teachClassService.queryById(bo.getClassId());
        if(ObjectUtils.isNotEmpty(teachClassVo)){
            bo.setYears(teachClassVo.getGrade());
        }
        if(CollectionUtils.isNotEmpty(files)){
            String upload = uploadFiles(files, bo);
            if(StringUtils.isEmpty(upload)){
                throw new ServiceException("添加失败");
            }
            bo.setFaceImage(upload);
        }
    }
    public static  String getFilePath(MemberBo bo,String tenantId){
        String url=new String();
        String path=baseStoreDir+"/"+tenantId+"/"+bo.getFileType();
        if(StringUtils.isNotEmpty(bo.getYears())) {
            path = path + "/" + bo.getYears();
        }
        File dir = new File(path);
        File[] files = dir.listFiles();
        if (files!= null) {
            for (File file : files) {
                if (file.isFile() && file.getName().contains(bo.getIdNumber())) {
                    url=file.getAbsolutePath();
                }
            }
        }
        return url;
    }
    public static  String getUrl(FaceImageVo faceImageVo){
        String url = "";
        String path=baseStoreDir+"/"+faceImageVo.getTenantId()+"/"+faceImageVo.getFileType();
        if(StringUtils.isNotEmpty(faceImageVo.getCollegeName())){
            path=path+"/"+faceImageVo.getCollegeName();
            File folder = new File(path);
            if (!folder.exists()) {
                boolean created = folder.mkdirs();
                if (!created) {
                    throw new ServiceException("文件上传失败");
                }
            }
            String newFileName = faceImageVo.getStuNum() +"."+faceImageVo.getPrefix();
            url = path+"/"+newFileName;
        }
        return url;
    }
}
